var newsModal; // 模态框          
/**
	 * 分页相关的配置
	 **/
const pagination = {
   
};

// 添加全局变量存储当前路径
var currentPath = document.getElementById('path').innerText;

/**
 * 按钮相关配置
 **/
const button = {
    // 按钮的类
    buttonsClass: 'default',
    // 类名前缀
    buttonsPrefix: 'btn'
}

/**
 * 图标相关配置
 **/
const icon = {
    // 图标前缀
    iconsPrefix: 'mdi',
    // 图标大小
    iconSize: 'mini',
    // 图标的设置
    icons: {
        columns: 'mdi-table-column-remove',
        paginationSwitchDown: 'mdi-door-closed',
        paginationSwitchUp: 'mdi-door-open',
        refresh: 'mdi-refresh',
        toggleOff: 'mdi-toggle-switch-off',
        toggleOn: 'mdi-toggle-switch',
        fullscreen: 'mdi-monitor-screenshot',
        detailOpen: 'mdi-plus',
        detailClose: 'mdi-minus'
    }
};
// 创建 CodeMirror 编辑器
var myCodeMirror = CodeMirror.fromTextArea(document.getElementById("myTextarea"), {
    lineNumbers: true,
    lineWrapping: true,
    lineNumbers: true,     // 显示行号
    tabSize:4,              //制表符
    indentUnit: 1,         // 缩进单位为2
    styleActiveLine: true, // 当前行背景高亮
    autoRefresh:true,       //打开自动刷新
    mode: 'javascript',     // python
    theme: 'monokai',      // 使用monokai模版
    // 启用自动补全
    hintOptions: {
        completeSingle: false,  // 当只有一个匹配项时不自动完成
        alignWithWord: true,    // 对齐单词
        closeOnUnfocus: true    // 失去焦点时关闭提示
    },
    // 额外的键盘映射
    extraKeys: {
        "Ctrl-Space": "autocomplete",    // Ctrl+Space 触发自动补全
        "Alt-/": "autocomplete",         // Alt+/ 触发自动补全
        "Ctrl-/": "toggleComment"        // Ctrl+/ 切换注释
    }
})

        
// 监听模态框的 "shown" 事件
$("#newsModal").on("shown.bs.modal", function () {
    // 让 CodeMirror 重新计算其大小和样式
    myCodeMirror.refresh();
});


// 保存文件函数
function saveFile() {
    // 获取编辑器的值
    var code = myCodeMirror.getValue();
    
    // 获取文件名
    var filename = $('#newsModal').find('.modal-title span').text();
   
    // 发送请求
    $.ajax({
        url: "/fife/SaveFileBody",
        method: "POST",
        data: {
            'path': filename,
            'code': code
        },
        success: function(data) {
            // alert(data.msg);
            layer.msg(data.msg)
        }
    });
}

// 获取文件大小
function get_path_size(fife_name){
    $.ajax({
        url: '/fife/get_path_size',
        type: 'post',
        data: {
            'path': (currentPath ? currentPath + '/' : '') + fife_name
        },
        dataType: 'json',
        success: function(data) {
            // alert(data.msg);
            layer.msg(data.msg)
        }
    });
}

// 添加切换目录的函数
function changeDirectory(newPath) {
    // 更新全局路径变量
    currentPath = newPath || '';
    
    // 更新页面上显示的路径
    document.getElementById('path').innerText = currentPath;
    
    // 重新加载表格数据
    $('#table').bootstrapTable('refresh', {
        url: '/fife/path?fife_name=' + currentPath,
        silent: true
    });
    
    // 更新面包屑导航
    updateBreadcrumb(currentPath);
}

// 更新面包屑导航
function updateBreadcrumb(path) {
    // 构造面包屑导航HTML
    var breadcrumbHtml = '当前目录：<a href="javascript:void(0);" onclick="changeDirectory(\'\')">根目录</a>';
    
    if (path) {
        var pathParts = path.split('/');
        var currentPathAcc = '';
        
        for (var i = 0; i < pathParts.length; i++) {
            if (pathParts[i] !== '') {
                if (currentPathAcc === '') {
                    currentPathAcc = pathParts[i];
                } else {
                    currentPathAcc += '/' + pathParts[i];
                }
                
                if (i === pathParts.length - 1) {
                    breadcrumbHtml += '/<span>' + pathParts[i] + '</span>';
                } else {
                    breadcrumbHtml += '/<a href="javascript:void(0);" onclick="changeDirectory(\'' + currentPathAcc + '\')">' + pathParts[i] + '</a>';
                }
            }
        }
    }
    
    // 更新面包屑导航
    var breadcrumbElement = document.querySelector('div[hidden]#path').nextElementSibling;
    if (breadcrumbElement) {
        breadcrumbElement.innerHTML = breadcrumbHtml;
    }
}

// 获取主题选择框元素
var input = document.getElementById("select");

// 定义一个函数，用于切换主题样式
function selectTheme() {
// 获取当前选择的主题名称
var theme = input.value;
// 设置编辑器的主题选项
myCodeMirror.setOption("theme", theme);
// 将主题名称存储到本地存储中，以便下次访问时保持一致
localStorage.setItem("theme", theme);
}

// 如果本地存储中有主题名称，就根据主题名称设置主题样式
var choice = localStorage.getItem("theme");
if (choice) {
input.value = choice;
selectTheme();
}
/**
 * 表格相关的配置
 **/
const table = {
    classes: 'table table-bordered table-hover table-striped lyear-table',
    // 请求地址
    url: '/fife/path?fife_name=' + currentPath,
    // 唯一ID字段
    uniqueId: 'id',
    // 每行的唯一标识字段
    idField: 'id',
    // 是否启用点击选中行
    clickToSelect: true,
    // 是否显示详细视图和列表视图的切换按钮(clickToSelect同时设置为true时点击会报错)
    // showToggle: true,
    // 请求得到的数据类型
    dataType: 'json',
    // 请求方法
    method: 'post',
    // 工具按钮容器
    toolbar: '#toolbar',
    // 是否分页
    pagination: true,
    pageSize:20,
    maintainSelected :true,
    // 是否显示所有的列
    showColumns: false,
    // 是否显示刷新按钮
    showRefresh: false,
    // 显示图标
    showButtonIcons: true,
    // 显示文本
    showButtonText: false,
    // 显示全屏
    showFullscreen: false,
    // 开关控制分页
    showPaginationSwitch: false,
    // 总数字段
    totalField: 'total',
    classes: "table table-bordered table-striped table-sm table-bordered table-striped",
    // 当字段为 undefined 显示
    undefinedText: '-',
    // 排序方式
    sortOrder: "asc",
    ...icon,
    ...pagination,
    ...button
};

/**
 * 用于演示的列信息
 **/
const columns = [{
    field: 'example',
    checkbox: true,
    // 列的宽度
    width: 5,
    // 宽度单位
    widthUnit: 'rem'
}, {
    field: 'fife_name',
    align: 'left',
    title: '文件名称',
    formatter:function(value, row, index){ 
        var value="";
       
        if (row.status == 0) {
            
            value = '<svg class="icon" style="font-size: 23px;"  aria-hidden="true"><use xlink:href="#icon-wenjianleixing-biaozhuntu-wenjianjia"></use></svg><a href="javascript:void(0);" onclick="changeDirectory(\'' + (currentPath ? currentPath + '/' + row.fife_name : row.fife_name) + '\')">&nbsp;' + row.fife_name + '</a>';
      
        } else if(row.fife_name.substring(row.fife_name.length - 4) == '.zip' || row.fife_name.substring(row.fife_name.length - 4) == '.rar' || row.fife_name.substring(row.fife_name.length - 4) == '.7z' || row.fife_name.substring(row.fife_name.length - 4) == '.tar'|| row.fife_name.substring(row.fife_name.length - 4) == 'r.gz'){
            
            value = '<svg class="icon"  style="font-size: 25px;" aria-hidden="true"><use xlink:href="#icon-yasuobao"></use></svg>&nbsp;'+row.fife_name ;
        }else if(row.fife_name.substring(row.fife_name.length - 3) == '.py' ){
            
            value = '<svg class="icon"  style="font-size: 25px;" aria-hidden="true"><use xlink:href="#icon-py"></use></svg>&nbsp;'+row.fife_name ;
        }else if(row.fife_name.substring(row.fife_name.length - 4) == 'html' ){
            
            value = '<svg class="icon"  style="font-size: 25px;" aria-hidden="true"><use xlink:href="#icon-HTML"></use></svg>&nbsp;'+row.fife_name ;
        }else if(row.fife_name.substring(row.fife_name.length - 4) == '.css' ){
            
            value = '<svg class="icon"  style="font-size: 25px;" aria-hidden="true"><use xlink:href="#icon-CSS"></use></svg>&nbsp;'+row.fife_name ;
        }
        else if(row.fife_name.substring(row.fife_name.length - 3) == '.js' ){
            
            value = '<svg class="icon"  style="font-size: 25px;" aria-hidden="true"><use xlink:href="#icon-javascript"></use></svg>&nbsp;'+row.fife_name ;
        }
        else if(row.fife_name.substring(row.fife_name.length - 4) == '.mp4' ){
            
            value = '<svg class="icon"  style="font-size: 25px;" aria-hidden="true"><use xlink:href="#icon-shipin"></use></svg>&nbsp;'+row.fife_name ;
        }else if(row.fife_name.substring(row.fife_name.length - 4) == '.php' ){
            
            value = '<svg class="icon"  style="font-size: 25px;" aria-hidden="true"><use xlink:href="#icon-icon-PHP"></use></svg>&nbsp;'+row.fife_name ;
        }
        else if(row.fife_name.substring(row.fife_name.length - 4) == '.png'|| row.fife_name.substring(row.fife_name.length - 4) == '.jpg'){
            
            value = '<svg class="icon"  style="font-size: 25px;" aria-hidden="true"><use xlink:href="#icon-tupian"></use></svg>&nbsp;'+row.fife_name ;
        }
        else{
            value = '<svg class="icon"  style="font-size: 25px;" aria-hidden="true"><use xlink:href="#icon-wenjian"></use></svg>&nbsp;'+row.fife_name ;

        }
        return value;
    }
   
}, {
    field: 'file_size',
    align: 'left',
    title: '文件大小',
    formatter:function(value, row, index){ 
        var value="";
       
        if (row.status == 0) {
            
            value = '<a href="#!" onclick="get_path_size()"> 计算</a>';
      
        } else {
            if (row.file_size < 1024) {
                value = row.file_size+'&nbsp;B';
            }else if(row.file_size < 1024*1024){
                value = (row.file_size/1024).toFixed(2)+'&nbsp;KB';
            }else{
                value = (row.file_size/1024/1024).toFixed(2)+'&nbsp;MB';
            }
            
        }
        return value;
    }
}, {
    field: 'modification_time',
    align: 'left',
    title: '修改时间'
}, {
    field: 'operate',
    title: '操作',
    formatter: btnGroup,  // 自定义方法
    events: {
        'click .edit-btn': function (event, value, row, index) {
            event.stopPropagation();
            editUser(row);
        },
        'click .del-btn': function (event, value, row, index) {
            event.stopPropagation();
            delUser(row);
        },
        'click .CopyFile-btn': function (event, value, row, index) {
            event.stopPropagation();
            copyFiler(row);
        },
        'click .MvFile2-btn': function (event, value, row, index) {
            event.stopPropagation();
            MvFile2(row);
        },
        'click .rename-btn': function (event, value, row, index) {
            event.stopPropagation();
            rename(row);
        },
        'click .compression-btn': function (event, value, row, index) {
            event.stopPropagation();
            compression(row);
        },
        'click .unzip-btn': function (event, value, row, index) {
            event.stopPropagation();
            unzip(row);
        },
        
        
    }
}];

// 自定义操作按钮
function btnGroup(value, row, index) {
    
    let html =
    `
    
    <div class="d-flex flex-nowrap">
    <button type="button" class="btn btn-link btn-sm  dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">操作</button>
    <ul class="dropdown-menu">
    <li><a class="dropdown-item edit-btn" href="#">编辑</a></li>
    <li><a class="dropdown-item del-btn" href="#">删除</a></li>
    <li><a class="dropdown-item CopyFile-btn" href="#">复制</a></li>
    <li><a class="dropdown-item MvFile2-btn" href="#">剪切</a></li>
    <li><a class="dropdown-item rename-btn" href="#">重命名</a></li>
    <li><a class="dropdown-item compression-btn" href="#">压缩</a></li>
  

    </ul>
   
  </div>

    `
         
    let html2 =

    `<div class="d-flex flex-nowrap">
    <button type="button" class="btn btn-link btn-sm  dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">操作</button>
    <ul class="dropdown-menu">
      <li><a class="dropdown-item CopyFile-btn" href="#">复制</a></li>
      <li><a class="dropdown-item MvFile2-btn" href="#">剪切</a></li>
      <li><a class="dropdown-item rename-btn" href="#">重命名</a></li>
      <li><a class="dropdown-item compression-btn" href="#">压缩</a></li>
      <li><a class="dropdown-item del-btn" href="#">删除</a></li>
    </ul>
  </div>
    
    `;

    let ziphtml =

    `<div class="d-flex flex-nowrap">
    <button type="button" class="btn btn-link btn-sm  dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">操作</button>
    <ul class="dropdown-menu">
      <li><a class="dropdown-item CopyFile-btn" href="#">复制</a></li>
      <li><a class="dropdown-item MvFile2-btn" href="#">剪切</a></li>
      <li><a class="dropdown-item rename-btn" href="#">重命名</a></li>
      <li><a class="dropdown-item unzip-btn" href="#">解压</a></li>
      <li><a class="dropdown-item del-btn" href="#">删除</a></li>
    </ul>
  </div>
      
    `
        let html4 =
    `
    
    <div class="d-flex flex-nowrap">
    <button type="button" class="btn btn-link btn-sm  dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">操作</button>
    <ul class="dropdown-menu">
    <li><a class="dropdown-item del-btn" href="#">删除</a></li>
    <li><a class="dropdown-item CopyFile-btn" href="#">复制</a></li>
    <li><a class="dropdown-item MvFile2-btn" href="#">剪切</a></li>
    <li><a class="dropdown-item rename-btn" href="#">重命名</a></li>
    <li><a class="dropdown-item compression-btn" href="#">压缩</a></li>
  

    </ul>
   
  </div>

    `
   ;
   
    
    //判断文件类型
    if(row.status == 0){
        return html2;
    }else if(row.fife_name.substring(row.fife_name.length - 4) == '.zip' || row.fife_name.substring(row.fife_name.length - 4) == '.rar' || row.fife_name.substring(row.fife_name.length - 4) == '.7z' || row.fife_name.substring(row.fife_name.length - 4) == '.tar'|| row.fife_name.substring(row.fife_name.length - 4) == 'r.gz'){
        return ziphtml;
    }else if(row.fife_name.substring(row.fife_name.length - 4) == '.jpg' || row.fife_name.substring(row.fife_name.length - 4) == '.png'){
        return html2;
    }else if(row.fife_name.substring(row.fife_name.length - 4) == '.exe'){
        return html4;
    }

    else{
        return html;}

        

}


// 自定义操作方法 - 编辑
function editUser(row) {
    

    $('#newsModal').find('.modal-title span').text((currentPath ? currentPath + '/' : '') + row.fife_name);
    $("#newsModal").modal("show");
    
    // 获取文件名的后缀
    var fileExtension = row.fife_name.split('.').pop();

    // 根据文件名的后缀设置CodeMirror的模式
    var mode;
    switch (fileExtension) {
        case 'html':
        case 'css':
            mode = 'htmlmixed';
            break;
        case 'js':
            mode = 'javascript';
            break;
        case 'php':
            mode = 'php';
            break;
        case 'py':
            mode = 'python';
            break;
        case 'java':
            mode = 'java';
            break;
        default:
            mode = 'text';
            break;
    }

    // 设置代码编辑器的值
    $.ajax({
        url: "/fife/GetFileBody",
        method: "POST",
        data: {
            'path': (currentPath ? currentPath + '/' : '') + row.fife_name,
        },
        success: function(data) {
          // 设置编辑器模式
          myCodeMirror.setOption('mode', mode);
          
          // 根据文件类型设置自动补全
          switch (fileExtension) {
              case 'js':
                  myCodeMirror.setOption('hintOptions', {
                      hint: CodeMirror.hint.javascript,
                      completeSingle: false,
                      alignWithWord: true,
                      closeOnUnfocus: true
                  });
                  break;
              case 'html':
                  myCodeMirror.setOption('hintOptions', {
                      hint: CodeMirror.hint.html,
                      completeSingle: false,
                      alignWithWord: true,
                      closeOnUnfocus: true
                  });
                  break;
              case 'css':
                  myCodeMirror.setOption('hintOptions', {
                      hint: CodeMirror.hint.css,
                      completeSingle: false,
                      alignWithWord: true,
                      closeOnUnfocus: true
                  });
                  break;
              case 'xml':
                  myCodeMirror.setOption('hintOptions', {
                      hint: CodeMirror.hint.xml,
                      completeSingle: false,
                      alignWithWord: true,
                      closeOnUnfocus: true
                  });
                  break;
              default:
                  myCodeMirror.setOption('hintOptions', {
                      hint: CodeMirror.hint.anyword,
                      completeSingle: false,
                      alignWithWord: true,
                      closeOnUnfocus: true
                  });
                  break;
          }
          
          // 设置编辑器内容
          myCodeMirror.setValue(data.data);
          // 刷新编辑器
          myCodeMirror.refresh();
        }
      });
}

//刷新数据
function sxsj() {
    // 获取表格对象
        var table = $('#table');
    // 调用refresh方法刷新表格
        table.bootstrapTable('refresh', {
        url: '/fife/path?fife_name=' + currentPath,
        silent: true
    });
        document.getElementById('select_single_line').innerHTML = ''
    }

function upload() {
    var uploadModal = layer.open({
        type: 1,
        title: '上传文件到：[ /' + currentPath + ' ] ---文件名请勿使用特殊字符',
        shadeClose: true,
        maxmin: true, //开启最大化最小化按钮
        area: ['90%', '85%'],
        content: `
        <!-- layui 样式引用 -->
        <link href="/static/layui/css/layui.css" rel="stylesheet">
        
        <div class="layui-upload" style="padding: 20px;">
          <button type="button" class="layui-btn layui-btn-normal" id="ID-upload-demo-files">
            <i class="layui-icon layui-icon-upload"></i> 选择多文件
          </button> 
          <button type="button" class="layui-btn layui-btn-warm" id="ID-upload-demo-files-action">
            <i class="layui-icon layui-icon-upload-circle"></i> 开始上传
          </button>
          
          <div class="layui-upload-list" style="margin-top: 15px;">
            <table class="layui-table">
              <colgroup>
                <col style="min-width: 200px;">
                <col width="120">
                <col width="200">
                <col width="120">
              </colgroup>
              <thead>
                <tr>
                  <th>文件名</th>
                  <th>大小</th>
                  <th>上传进度</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody id="ID-upload-demo-files-list"></tbody>
            </table>
          </div>
        </div>
        
        <!-- layui 脚本引用 -->
        <script src="/static/layui/layui.js"></script>
        `,
        success: function(layero, index) {
            // layui 上传组件初始化
            layui.use(function(){
                var upload = layui.upload;
                var element = layui.element;
                var $ = layui.$;
                
                // 制作多文件上传表格 - 手动实现分片上传
                var selectedFiles = {}; // 全局变量存储选择的文件
                
                var uploadListIns = upload.render({
                    elem: '#ID-upload-demo-files',
                    elemList: $('#ID-upload-demo-files-list'),
                    url: '/fife/upload_api', // 上传接口
                    accept: 'file',
                    multiple: true,
                    number: 10, // 最大上传数量
                    auto: false, // 不自动上传
                    bindAction: '#ID-upload-demo-files-action',
                    // 不使用layui的分片，手动实现
                    choose: function(obj) {
                        var that = this;
                        var files = this.files = obj.pushFile(); // 将每次选择的文件追加到文件队列
                        
                        // 将文件存储到全局变量中
                        selectedFiles = files;
                        
                        console.log('文件选择完成，文件数量:', Object.keys(files).length);
                        console.log('选择的文件:', files);
                        console.log('全局文件存储:', selectedFiles);
                        
                        // 读取本地文件
                        obj.preview(function(index, file, result) {
                            console.log('预览文件:', index, file.name, file.size);
                            
                            var tr = $(['<tr id="upload-' + index + '">',
                                '<td>' + file.name + '</td>',
                                '<td>' + (file.size / 1024 / 1024).toFixed(2) + 'MB</td>',
                                '<td><div class="layui-progress" lay-filter="progress-demo-' + index + '"><div class="layui-progress-bar" lay-percent=""></div></div></td>',
                                '<td>',
                                    '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>',
                                    '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>',
                                '</td>',
                            '</tr>'].join(''));
                            
                            // 单个重传
                            tr.find('.demo-reload').on('click', function() {
                                startChunkUpload(file, index, element);
                            });
                            
                            // 删除文件
                            tr.find('.demo-delete').on('click', function() {
                                delete files[index];
                                delete selectedFiles[index]; // 也从全局变量中删除
                                tr.remove();
                                uploadListIns.config.elem.next()[0].value = '';
                                console.log('删除文件后，剩余文件数量:', Object.keys(selectedFiles).length);
                            });
                            
                            that.elemList.append(tr);
                            element.render('progress');
                        });
                    }
                });
                
                // 重写上传动作，启动手动分片上传
                $('#ID-upload-demo-files-action').off('click').on('click', function() {
                    // 使用全局变量 selectedFiles
                    console.log('点击开始上传，检查文件:', selectedFiles);
                    console.log('文件数量:', selectedFiles ? Object.keys(selectedFiles).length : 0);
                    
                    if (!selectedFiles || Object.keys(selectedFiles).length === 0) {
                        layer.msg('请先选择文件', {icon: 2});
                        return;
                    }
                    
                    // 开始上传所有文件
                    var fileKeys = Object.keys(selectedFiles);
                    console.log('开始上传文件:', fileKeys);
                    
                    for (var i = 0; i < fileKeys.length; i++) {
                        var fileIndex = fileKeys[i];
                        var file = selectedFiles[fileIndex];
                        console.log('上传文件:', fileIndex, file.name);
                        startChunkUpload(file, fileIndex, element);
                    }
                });
                
                // 手动实现分片上传函数
                function startChunkUpload(file, index, element) {
                    var chunkSize = 2097152; // 2MB
                    var totalChunks = Math.ceil(file.size / chunkSize);
                    var currentChunk = 0;
                    
                    console.log('开始分片上传:', {
                        fileName: file.name,
                        fileSize: file.size,
                        totalChunks: totalChunks,
                        chunkSize: chunkSize
                    });
                    
                    // 更新状态
                    var tr = $('#upload-' + index);
                    var tds = tr.children();
                    tds.eq(3).html('<span class="layui-badge layui-bg-blue">分片上传中...</span>');
                    
                    function uploadNextChunk() {
                        if (currentChunk >= totalChunks) {
                            return;
                        }
                        
                        var start = currentChunk * chunkSize;
                        var end = Math.min(start + chunkSize, file.size);
                        var chunk = file.slice(start, end);
                        
                        var formData = new FormData();
                        formData.append('file', chunk);
                        formData.append('fileName', file.name);
                        formData.append('chunkIndex', currentChunk);
                        formData.append('totalChunks', totalChunks);
                        formData.append('path', currentPath);
                        
                        console.log('上传分片:', currentChunk + 1, '/', totalChunks);
                        console.log('FormData 内容检查:');
                        console.log('  fileName:', file.name);
                        console.log('  chunkIndex:', currentChunk);
                        console.log('  totalChunks:', totalChunks);
                        console.log('  path:', currentPath);
                        console.log('  chunk size:', chunk.size);
                        
                        // 验证FormData内容
                        for (let pair of formData.entries()) {
                            console.log('  FormData entry:', pair[0], '=', pair[1]);
                        }
                        
                        $.ajax({
                            url: '/fife/upload_api',
                            type: 'POST',
                            data: formData,
                            processData: false,
                            contentType: false,
                            cache: false,  // 禁用缓存
                            xhr: function() {
                                var xhr = new XMLHttpRequest();
                                xhr.upload.addEventListener('progress', function(e) {
                                    if (e.lengthComputable) {
                                        var chunkProgress = (e.loaded / e.total) * 100;
                                        var totalProgress = ((currentChunk + chunkProgress / 100) / totalChunks) * 100;
                                        element.progress('progress-demo-' + index, Math.round(totalProgress) + '%');
                                    }
                                });
                                return xhr;
                            },
                            success: function(res) {
                                console.log('分片', currentChunk, '上传响应:', res);
                                
                                if (res.code === 200) {
                                    currentChunk++;
                                    
                                    // 检查是否是最后一个分片
                                    if (res.data && res.data.isComplete) {
                                        // 文件上传完成
                                        tds.eq(3).html('<span class="layui-badge layui-bg-green">完成</span>');
                                        element.progress('progress-demo-' + index, '100%');
                                        layer.msg('文件 "' + file.name + '" 上传并合并成功', {icon: 1});
                                        
                                        // 检查是否所有文件都完成
                                        setTimeout(function() {
                                            var completedFiles = $('.layui-badge layui-bg-green').length;
                                            var totalFiles = $('[id^="upload-"]').length;
                                            console.log('已完成文件数:', completedFiles, '/', totalFiles);
                                            
                                            if (completedFiles === totalFiles) {
                                                // 所有文件都上传完成
                                                setTimeout(function() {
                                                    layer.msg('所有文件上传完成！', {icon: 1, time: 2000});
                                                    sxsj(); // 刷新文件列表
                                                    // 添加额外的刷新保障
                                                    setTimeout(function() {
                                                        sxsj();
                                                    }, 1500);
                                                    
                                                    // 关闭上传弹窗
                                                    setTimeout(function() {
                                                        layer.close(uploadModal);
                                                    }, 2000);
                                                }, 1000);
                                            } else {
                                                // 添加额外的刷新保障，即使不是所有文件都完成也尝试刷新
                                                setTimeout(function() {
                                                    sxsj();
                                                }, 1500);
                                            }
                                        }, 500);
                                    } else {
                                        // 继续上传下一个分片
                                        uploadNextChunk();
                                    }
                                } else {
                                    console.error('分片上传失败:', res);
                                    tds.eq(3).html('<span class="layui-badge layui-bg-red">失败</span>');
                                    tds.eq(3).find('.demo-reload').removeClass('layui-hide');
                                    layer.msg('分片上传失败: ' + (res.msg || '未知错误'), {icon: 2});
                                }
                            },
                            error: function(xhr, status, error) {
                                console.error('分片上传请求失败:', {
                                    status: xhr.status,
                                    statusText: xhr.statusText,
                                    responseText: xhr.responseText,
                                    error: error
                                });
                                
                                var errorMsg = error;
                                try {
                                    var response = JSON.parse(xhr.responseText);
                                    if (response && response.msg) {
                                        errorMsg = response.msg;
                                    }
                                } catch (e) {
                                    console.log('无法解析错误响应');
                                }
                                
                                tds.eq(3).html('<span class="layui-badge layui-bg-red">失败</span>');
                                tds.eq(3).find('.demo-reload').removeClass('layui-hide');
                                layer.msg('分片上传请求失败: ' + errorMsg, {icon: 2});
                            }
                        });
                    }
                    
                    // 开始上传第一个分片
                    uploadNextChunk();
                }
            });
        }
    });
}

//关闭弹窗
                  

// 自定义方法 - 删除
function delUser(row) {
    $.confirm({
        title: '删除',
        content: '删除操作不可恢复，你确定？',
        autoClose: 'cancelAction|10000',
        escapeKey: 'cancelAction',
        buttons: {
            confirm: {
                btnClass: 'btn-red',
                text: '删除',
                action: function () {
                    // 发送ajax请求
                    $.ajax({
                        url: "/fife/DeleteFile",
                        method: "POST",
                        data: {
                            'path': (currentPath ? currentPath + '/' : '') + row.fife_name,
                        },
                        success: function(data) {
                            layer.msg(data.msg,{icon: 'success'})
                            sxsj()
                          
                        }
                      });
                }
            },
            cancelAction: {
                text: '取消',
                action: function () {
                    $.alert('刚刚得救了！');
                }
            }
        }
    });

    
    
}
// 自定义方法 - 复制
function copyFiler(row) {
    layer.msg('请选择合适的地方粘贴');
    sessionStorage.setItem('copyFilerpath', (currentPath ? currentPath + '/' : '') + row.fife_name);
    sessionStorage.setItem('copyFilename', row.fife_name);
    // 更新div的文本内容
    $("#shear").html('<button style="float: right; margin-left:10px;" class="btn btn-sm btn-dark float-right" onclick="copyfife()">粘贴</button>')
    document.getElementById('select_single_line').innerHTML = ''
    
}  

// 自定义方法 - 复制
function copyfife() {
    
    // 发送ajax请求
    $.ajax({
        url: "/fife/CopyFile",
        method: "POST",
        data: {
            'sfile' : sessionStorage.getItem('copyFilerpath'),
            'dfile': (currentPath ? currentPath + '/' : '') + sessionStorage.getItem('copyFilename'),
        },
        success: function(data) {
            layer.msg(data.msg,{icon: 'success'})
            sessionStorage.removeItem('copyFilerpath');
            sessionStorage.removeItem('copyFilename');
            sxsj()
          
        }
      });
}

// 自定义方法 - 剪切
function MvFile2(row) {
    layer.msg('请选择合适的地方粘贴');
    sessionStorage.setItem('copyFilerpath2', (currentPath ? currentPath + '/' : '') + row.fife_name);
    sessionStorage.setItem('copyFilename2', row.fife_name);
    // 更新div的文本内容
    $("#shear").html('<button style="float: right; margin-left:10px;" class="btn btn-sm btn-dark float-right" onclick="copyfife2()">粘贴</button>')
    document.getElementById('select_single_line').innerHTML = ''
      
}  

// 自定义方法 - 剪切
function copyfife2() {
    
    // 发送ajax请求
    $.ajax({
        url: "/fife/MvFile2",
        method: "POST",
        data: {
            'sfile' : sessionStorage.getItem('copyFilerpath2'),
            'dfile': (currentPath ? currentPath + '/' : '') + sessionStorage.getItem('copyFilename2'),
        },
        success: function(data) {
            layer.msg(data.msg,{icon: 'success'})
            sessionStorage.removeItem('copyFilerpath2');
            sessionStorage.removeItem('copyFilename2');
            sxsj()
          
        }
      });
}

//自定义方法 -重命名
function rename(row) {

    $.confirm({
        title: '新名称',
        //content: 'url:form.html',  // 也可以采用url形式
        content: '<div class="form-group p-1 mb-0">' +
            '  <input autofocus="" type="text" id="input-name" value="'+row.fife_name+'" class="form-control">' +
            '</div>',
        buttons: {
            sayMyName: {
                text: '确认',
                btnClass: 'btn-orange',
                action: function () {
                    var input = this.$content.find('input#input-name');
                    if (!$.trim(input.val())) {
                        $.alert({
                            content: "字段不能为空。",
                            type: 'red'
                        });
                        return false;
                    } else {
                        $.ajax({
                            url: "/fife/MvFile3",
                            type: "POST",
                            data: {
                                'sfile': (currentPath ? currentPath + '/' : '') + row.fife_name,
                                'dfile': (currentPath ? currentPath + '/' : '') + input.val(),
                            },
                            success: (data) => {
                                layer.msg(data.msg,{icon: 'success'});
                                sxsj()


                            }
                        });

                    }
                }
            },
            '稍等': function () {
            }
        }
    });


}

// 自定义方法 - 压缩
function compression(row) {
    $.confirm({
        title: '压缩文件',
        //content: 'url:form.html',  // 也可以采用url形式
        content: '<div class="form-group p-1 mb-0" >' + 
                 '  <label class="control-label">压缩类型</label>' +
                 '  <select class="form-control" id="compression_type" onchange="compression_type()">' +
                '   <option value="tar.gz">tar.gz (推荐)</option>' +
                '   <option value="zip">zip (通用格式)</option>' +
                '   <option value="zip">rar (WinRAR对中文兼容较好)</option>' +
                '   <option value="7z">7z (压缩率极高的压缩格式)</option>'+
                ' </select>' +
                 '</div>' +
                 '<div class="form-group p-1 mb-0">' +
                ' <label class="control-label">压缩路径</label>' +
                 '  <input autofocus="" type="text" id="input-name" value='+row.fife_name+'_'+randomLetters.join('')+'.tar.gz'+' class="form-control">' +
                 '</div>',
                 
        buttons: {
            sayMyName: {
                text: '压缩',
                btnClass: 'btn-orange',
                action: function() {
                    var input = this.$content.find('input#input-name');
                    var compression_type=this.$content.find('select#compression_type');
                    {
                        //发送ajax请求
                        $.ajax({
                            url: "/fife/Zip",
                            method: "POST",
                            data: {
                               'sfile' : row.fife_name,
                                'dfile': (currentPath ? currentPath + '/' : '') + input.val(),
                                'z_type':compression_type.val(),
                                'path':currentPath,
                            },
                            success: function(data) {
                                layer.msg(data.msg,{icon: 'success'})
                                sxsj()
                                
                            }
                        });
                    }
                }
            },
            '关闭': function() {}
        }
    });
}

// 自定义方法 - 解压
function unzip(row) {
    $.confirm({
        title: '解压',
        //content: 'url:form.html',  // 也可以采用url形式
        content:  
                 '<div class="form-group p-1 mb-0">' +
                ' <label class="control-label">文件名</label>' +
                 '  <input autofocus="" type="text" id="input-name" value='+row.fife_name+' class="form-control">' +
                 '</div>'+
                 '<div class="form-group p-1 mb-0">' +
                 ' <label class="control-label">解压到</label>' +
                ' <input autofocus="" type="text" id="input-name" value='+(currentPath ? currentPath + '/' : '')+' class="form-control">' +
                 '</div>',
                 
                 
        buttons: {
            sayMyName: {
                text: '解压',
                btnClass: 'btn-orange',
                action: function() {
                    var input = this.$content.find('input#input-name');
                    var compression_type=this.$content.find('select#compression_type');
                    {
                        //发送ajax请求
                        $.ajax({
                            url: "/fife/unzip",
                            method: "POST",
                            data: {
                               'sfile' : row.fife_name,
                                'dfile': currentPath
                               
                            },
                            success: function(data) {
                                layer.msg(data.msg,{icon: 'success'})
                                sxsj()
                                
                            }
                        });
                    }
                }
            },
            '关闭': function() {}
        }
    });
}

// 生成随机数
function getRandomLetter() {
    let letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    let letter = letters[Math.floor(Math.random() * letters.length)];
    return letter;
}

let randomLetters = [];
for (let i = 0; i < 6; i++) {
    randomLetters.push(getRandomLetter());
}
function compression_type() {  
    var x = document.getElementById("compression_type").value;
     // 获取输入框元素  
     var inputElement = document.getElementById('input-name');  
       // 改变输入框的值  
       inputElement.value = (currentPath ? currentPath + '/' : '') + '_' + randomLetters.join('') + '.' + x;  

   
  }
// 判断copyFilerpath是否有数据

if(sessionStorage.getItem('copyFilerpath') == null){
        
}else{
    $("#shear").html('<button style="float: right; margin-left:10px;" class="btn btn-sm btn-dark float-right" onclick="copyfife()">粘贴</button>')

}
// 判断copyFilerpath是否有数据

if(sessionStorage.getItem('copyFilerpath2') == null){
        
}else{
    $("#shear").html('<button style="float: right; margin-left:10px;" class="btn btn-sm btn-dark float-right" onclick="copyfife2()">粘贴</button>')

}

    
//选择单行
$('#table').on('check.bs.table', function (e, row, $element) {
    document.getElementById('select_single_line').innerHTML = '<button style="float: right; margin-left:10px;"  class="btn btn-sm btn-danger float-right" onclick="getSels()">删除</button>' +
        '<button style="float: right; margin-left:10px;"  class="btn btn-sm btn-primary float-right" onclick="cutfife()">剪切</button>' +
        '<button style="float: right; margin-left:10px;"  class="btn btn-sm btn-dark float-right" onclick="all_selected_compress()">压缩</button>';
});

//取消单行选择
$('#table').on('uncheck.bs.table', function (e, rowsAfter, rowsBefore) {
    
    // document.getElementById('select_single_line').innerHTML = ''
});

//全选事件
$('#table').on('check-all.bs.table', function (e, rowsAfter, rowsBefore) {
    document.getElementById('select_single_line').innerHTML = '<button style="float: right; margin-left:10px;"  class="btn btn-sm btn-danger float-right" onclick="getSels()">删除</button>' +
        '<button style="float: right; margin-left:10px;"  class="btn btn-sm btn-primary float-right" onclick="cutfife()">剪切</button>' +
        '<button style="float: right; margin-left:10px;"  class="btn btn-sm btn-dark float-right" onclick="all_selected_compress()">压缩</button>';
});
//取消全选
$('#table').on('uncheck-all.bs.table', function (e, rowsAfter, rowsBefore) {
    document.getElementById('select_single_line').innerHTML = ''
});



// 多选删除文件
function getSels(){
    var rows = $("#table").bootstrapTable('getSelections');// 获得要删除的数据
    $.confirm({
        title: '删除',
        content: '删除操作不可恢复，你确定？',
        autoClose: 'cancelAction|10000',
        escapeKey: 'cancelAction',
        buttons: {
            confirm: {
                btnClass: 'btn-red',
                text: '删除',
                action: function () {
                    var ids = new Array();// 声明一个数组
                    $(rows).each(function () {// 通过获得别选中的来进行遍历
                        ids.push(this.fife_name);// cid为获得到的整条数据中的一列
                        

                    });
                    // 发送ajax请求
                    $.ajax({
                        url: '/fife/SetBatchData',
                        type: 'POST',
                        data: {

                            'path':currentPath,
                            'ids': JSON.stringify(ids)
                        },
                       
                        success: function (data) {
                            layer.msg(data.msg,{icon: 'success'})
                            sxsj()
                            
                        }
                    });
                }
            },
            cancelAction: {
                text: '取消',
                action: function () {
                    $.alert('刚刚得救了！');
                }
            }
        }
    });


}
// 多选压缩
function all_selected_compress(){
    var rows = $('#table').bootstrapTable('getSelections');              
    let fileNames = rows.map(file => file.fife_name).join(',');
    $.confirm({
        title: '压缩文件',
        //content: 'url:form.html',  // 也可以采用url形式
        content: '<div class="form-group p-1 mb-0" >' + 
                 '  <label class="control-label">压缩类型</label>' +
                 '  <select class="form-control" id="compression_type" onchange="compression_type()">' +
                '   <option value="tar.gz">tar.gz (推荐)</option>' +
                '   <option value="zip">zip (通用格式)</option>' +
                '   <option value="zip">rar (WinRAR对中文兼容较好)</option>' +
                '   <option value="7z">7z (压缩率极高的压缩格式)</option>'+
                ' </select>' +
                 '</div>' +
                 '<div class="form-group p-1 mb-0">' +
                ' <label class="control-label">压缩路径</label>' +
                 '  <input autofocus="" type="text" id="input-name" value=ALL'+randomLetters.join('')+'.tar.gz'+' class="form-control">' +
                 '</div>',
                 
        buttons: {
            sayMyName: {
                text: '压缩',
                btnClass: 'btn-orange',
                action: function() {
                    var input = this.$content.find('input#input-name');
                    var compression_type=this.$content.find('select#compression_type');
                    {
                        //发送ajax请求
                        $.ajax({
                        url: '/fife/Zip',
                        type: 'POST',
                        data: {

                            'sfile':fileNames,
                            'dfile': (currentPath ? currentPath + '/' : '') + input.val(),
                            'z_type':compression_type.val(),
                            'path':currentPath,
                        },
                       
                        success: function (data) {
                            layer.msg(data.msg,{icon: 'success'})
                            sxsj()
                            
                        }
                    });
                        
                    }
                }
            },
            '关闭': function() {}
        }
    });

}

$('table').bootstrapTable({
    ...table,
    // 自定义的查询参数
    queryParams: function (params) {
        return {
            // 每页数据量
            limit: params.limit,
            // sql语句起始索引
            offset: params.offset,
            page: (params.offset / params.limit) + 1,
            // 排序的列名
            sort: params.sort,
            // 排序方式 'asc' 'desc'
            sortOrder: params.order
        };
    },
    columns,
    onLoadSuccess: function(data){
        // $("[data-bs-toggle='tooltip']").tooltip();
    }
});
    





// 刷新表格
function shuaxin() {
    // 获取表格对象
        var table = $('#table');
    // 调用refresh方法刷新表格
        table.bootstrapTable('refresh', {
        url: '/fife/path?fife_name=' + currentPath,
        silent: true
    });
        document.getElementById('select_single_line').innerHTML = ''
    
    
    }



// 新建文件夹
function CreateDir(){
   $.confirm({
        title: '文件夹名称',
        //content: 'url:form.html',  // 也可以采用url形式
        content: '<div class="form-group p-1 mb-0">' +
            '  <input autofocus="" type="text" id="input-name" placeholder="请输入文件名称" class="form-control">' +
            '</div>',
        buttons: {
            sayMyName: {
                text: '确认',
                btnClass: 'btn-orange',
                action: function () {
                    var input = this.$content.find('input#input-name');
                    if (!$.trim(input.val())) {
                        $.alert({
                            content: "字段不能为空。",
                            type: 'red'
                        });
                        return false;
                    } else {
                        $.ajax({
                            url: "/fife/CreateDir",
                            type: "POST",
                            data: {
                                'path': (currentPath ? currentPath + '/' : '') + input.val(),
                            },
                            success: (data) => {
                               
                                // 刷新当前页面
                                sxsj()
                                layer.msg(data.msg);

                            }
                        });

                    }
                }
            },
            '稍等': function () {
            }
        }
    });


}
// 新建文件
function CreateFile(){
    $.confirm({
        title: '文件名称',
        //content: 'url:form.html',  // 也可以采用url形式
        content: '<div class="form-group p-1 mb-0">' +
            '  <input autofocus="" type="text" id="input-name" placeholder="请输入文件名称" class="form-control">' +
            '</div>',
        buttons: {
            sayMyName: {
                text: '确认',
                btnClass: 'btn-orange',
                action: function () {
                    var input = this.$content.find('input#input-name');
                    if (!$.trim(input.val())) {
                        $.alert({
                            content: "字段不能为空。",
                            type: 'red'
                        });
                        return false;
                    } else {
                        $.ajax({
                            url: "/fife/CreateFile",
                            type: "POST",
                            data: {
                                'path': (currentPath ? currentPath + '/' : '') + input.val(),
                            },
                            success: (data) => {
                               
                                // 刷新当前页面
                                sxsj()
                                layer.msg(data.msg);

                            }
                        });

                    }
                }
            },
            '稍等': function () {
            }
        }
    });


}
// 批量剪切文件
function cutfife() {

    var rows = $('#table').bootstrapTable("getSelections");
    layer.msg('请选择合适的地方粘贴');
    // 缓存
    // 存储数据
    sessionStorage.setItem('rows', JSON.stringify(rows));
    sessionStorage.setItem('path', currentPath);
  
    // 更新div的文本内容
    $("#shear").html('<button style="float: right; margin-left:10px;" class="btn btn-sm btn-dark float-right" onclick="paste_file()">粘贴</button>')
    document.getElementById('select_single_line').innerHTML = ''
    

}
// 获取数据
let rows = sessionStorage.getItem('rows');
if (rows) {
    $("#shear").html('<button style="float: right; margin-left:10px;" class="btn btn-sm btn-dark float-right" onclick="paste_file()">粘贴</button>')
}else {
    // 输出: null
    // document.getElementById('shear').innerHTML = ''
}

function paste_file() {
    document.getElementById('shear').innerHTML = ''
    
    $.ajax({
        url: "/fife/MvFile",
        type: "POST",
        data: {
            'data': sessionStorage.getItem('rows'),
            'sfile' : sessionStorage.getItem('path'),
            'dfile': currentPath
            
        },
        success: (data) => {
           
            // 刷新当前页面
            sxsj()
            layer.msg(data.msg);
            sessionStorage.removeItem('rows');

        }
    });

    
    

}